<template>
  <div class="public_page_style">
    <div
        v-loading="loading"
        class="personal_center"
        element-loading-text="上传头像中..."
    >
      <h2>个人中心</h2>

      <el-button type="primary" @click="uploadAvatar">修改头像</el-button>
      <input class="uploadA" style="display: none" type="file">
      <img :src="$store.getters['user/avatar']" alt="" class="preview">

    </div>
  </div>
</template>

<script>

export default {
  name: "PersonalCenter",
  data() {
    return {
      loading: false
    }
  },
  methods: {
    uploadAvatar() {
      const uploadA = document.querySelector('input[type="file"]')
      uploadA.click()

      uploadA.onchange = e => {
        const file = e.target.files[0]
        const reader = new FileReader()
        this.loading = true

        reader.onload = e => {
          const base64Image = e.target.result
          this.$store.dispatch('user/setAvatar', base64Image).finally(() => {
            this.loading = false
            this.$message.success('头像修改成功')
          })
        }
        reader.readAsDataURL(file)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.personal_center {
  width: 100%;
  height: 100%;
  background: #ffffff;
  border-radius: 2vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 2vh;

  h2 {
    margin-bottom: 2vh;
  }

  .preview {
    width: 5vw;
    height: 5vw;
  }

  .preview {
    margin-top: 2vh;
  }
}
</style>
